<?php

namespace app\api\controller;
use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\SystemConfig;
use app\api\service\OrderService;
use app\api\service\RoomService;
use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Lights;
use app\common\model\Occupants;
use app\common\model\Rooms;
use app\manystore\model\ManystoreShop;
use think\Db;

/**
 * 预约
 */
class Reservations extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Reservations();
    }

    //预约
    public function reservation(){
        $men = input('men') ;
        if($men==''){
            $men=0;
        }
        $women = input('women', 0);
        if($women==''){
            $women=0;
        }
        if ($women==0&&$men==0) {
            $this->error(__('请选择人数'));
        }
        if (!$phone = input('phone')) {
            $this->error(__('请输入联系电话'));
        }
        if (!$shop_id = input('shop_id')) {
            $this->error(__('请选择门店'));
        }
        if (!isValidPhoneNumber($phone)) {
            $this->error(__('手机号格式不正确'));
        }

        if (input('is_put')===""||input('is_put')===null) {
            $this->error(__('请选择是否拼桌'));
        }
        if (!$start_time = input('start_time')) {
            $this->error(__('请选择开始时间'));
        }
        if (!$end_time = input('end_time')) {
            $this->error(__('请选择结束时间'));
        }
        if (!$room_id= input('room_id')) {
            $this->error(__('请选择房间'));
        }
        $room=Rooms::where('id','=',$room_id)->find();
        if(!$room){
            $this->error(__('房间不存在'));
        }
        $user=\app\common\model\User::where('id','=',$this->auth->id)->find();
        // 用户余额
        $user_balance = $user->money;

        // 押金
        $shop=\app\common\model\manystore\Shop::where('id','=',$shop_id)->find();


        $timeDifference = strtotime($end_time) - strtotime($start_time);
        // 转换为分钟
        $minutesDifference = $timeDifference / 60/$shop['interval'];


        $total_people = $men + $women;
        $deposit_amount = $room['deposit'] * $total_people*1;

        // 计算余额抵扣金额
        $balance_deduction = 0;
        $final_amount = $deposit_amount; // 默认支付金额为押金

        // 判断余额是否足够抵扣押金
        if ($user_balance >= $final_amount) {
            // 如果余额足够，则全额抵扣
            $balance_deduction = $final_amount; // 抵扣的余额
            $final_amount = 0; // 余额抵扣后剩余的金额
        } else {
            // 如果余额不足，用余额抵扣某部分
            $balance_deduction = $user_balance; // 最大可以抵扣的金额
            $final_amount = $deposit_amount - $balance_deduction; // 实际需要支付的金额
        }


        $final_amount = max(0, $final_amount);

        $pd=\app\common\model\Reservations::where('user_id',$this->auth->id)->where('reservation_status','<>',2)->where('deposit_status',1)->find();
        if($pd){
            $this->error(__('您有其他预约房间'));
        }
// 创建预约记录
        $result = \app\common\model\Reservations::create([
            'room_id' => $room_id,
            'shop_id'=>$shop_id,
            'number_of_men' => $men,
            'number_of_women' => $women,
            'phone' => $phone,
            'user_id' => $this->auth->id,
            'is_put' => input('is_put'),
            'start_time' => $start_time,
            'end_time' => $end_time,
            'number_of_people' => $total_people,
            'balance_deduction' => $balance_deduction,
            'final_amount' => $final_amount,
            'deposit' => $deposit_amount,
            'expire_pay_time'=>time() + 15 * 60,
            'order_no'=>order_no(),
            'deposit_status' => ($final_amount == 0) ? 1 : 0, // 设置为已支付或待支付
            'pay_time' => ($final_amount == 0) ? time() : null // 设置为已支付或待支付

        ]);

        // 仅在余额足够的情况下扣除余额
        if ($balance_deduction > 0 && $final_amount == 0) {
           \app\common\model\User::money(-$balance_deduction,$this->auth->id,'预约押金');
        }
        if($result){
            if($final_amount==0){
                $this->success('请求成功', [
                    'is_pay' => 0,
                    'id' => $result->id,
                    'order_no' => $result->order_no,
                ]);
            }else{
                $this->success('请求成功', [
                    'is_pay' => 1,
                    'id' => $result->id,
                    'order_no' => $result->order_no,
                ]);
            }
        }else{
            $this->error(__('预约失败'));
        }


    }

    //  重新支付
    public function again_payment()
    {


        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $Reservations = \app\common\model\Reservations::where('id', '=', $id)->find();
        if ($Reservations['deposit_status'] != 0) {
            $this->error('当前订单已支付');
        }
        $deposit_amount = $Reservations['deposit'];

        DB::startTrans();
        //重新计算支付所需的金额
        $user = \app\common\model\User::where('id', '=', $this->auth->id)->find();
        // 用户余额
        $user_balance = $user->money;
        // 计算余额抵扣金额
        $balance_deduction = 0;
        $final_amount = $deposit_amount; // 默认支付金额为押金

        // 判断余额是否足够抵扣押金
        if ($user_balance >= $final_amount) {
            // 如果余额足够，则全额抵扣
            $balance_deduction = $final_amount; // 抵扣的余额
            $final_amount = 0; // 余额抵扣后剩余的金额
        } else {
            // 如果余额不足，用余额抵扣某部分
            $balance_deduction = $user_balance; // 最大可以抵扣的金额
            $final_amount = $deposit_amount - $balance_deduction; // 实际需要支付的金额
        }
        $final_amount = max(0, $final_amount);
        $pd = \app\common\model\Reservations::where('user_id', $this->auth->id)->where('reservation_status', '<>', 2)->where('deposit_status', 1)->find();
        if ($pd) {
            $this->error(__('您有其他预约房间'));
        }

        // 仅在余额足够的情况下扣除余额
        if ($balance_deduction > 0 && $final_amount == 0) {
            \app\common\model\User::money(-$balance_deduction, $this->auth->id, '预约押金');
        }

        \app\common\model\Reservations::where('id', '=', $id)->update(['balance_deduction' => $balance_deduction, 'final_amount' => $final_amount,'deposit_status'=>($final_amount == 0) ? 1 : 0,'pay_time'=>($final_amount == 0) ? time() : null]);
        db::commit();
        if ($final_amount == 0) {
            $this->success('请求成功', [
                'is_pay' => 0,
                'id' => $Reservations['id'],
                'order_no' => $Reservations['order_no'],
            ]);
        } else {
            $this->success('请求成功', [
                'is_pay' => 1,
                'id' => $Reservations['id'],
                'order_no' => $Reservations['order_no'],
            ]);
        }

    }




    //支付押金

    public function reservation_payment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $order_no = order_no();
        //重置订单号
        $result=\app\common\model\Reservations::where('id','=',$id)->where('deposit_status','=',0)->update(['order_no'=>$order_no]);
        if($result===0){
            $this->error('当前订单已支付');
        }
        $payment = OrderService::reservation_payment($id, $this->auth->id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }


    //预约的时间段
    public function reservation_time() {
        if (!$shop_id = input('shop_id')) {
            $this->error(__('请选择门店'));
        }
        $shop = ManystoreShop::where('id', '=', $shop_id)->find();
        $interval = $shop['interval']; // 间隔时间 分钟
        $opening_time = strtotime($shop['opening_time']); // 营业时间
        $closing_time = strtotime($shop['closing_time']); // 关门时间

        $today = strtotime('today');
        $dateList = []; // 使用数组来存储结果

        // 中文星期对应数组
        $weekdays = ['日', '一', '二', '三', '四', '五', '六'];

        // 生成今天到未来七天的日期
        for ($i = 0; $i < 7; $i++) {
            $current_date = strtotime("+" . $i . " days", $today); // 当前日期（时间戳）

            // 显示“月-日”格式
            $date_label = date('m-d', $current_date);

            // 显示“今天”、“明天”、“后天”或“周几”
            if ($i == 0) {
                $weekday_label = '今天';
            } elseif ($i == 1) {
                $weekday_label = '明天';
            } elseif ($i == 2) {
                $weekday_label = '后天';
            } else {
                $weekday_label = '周' . $weekdays[date('w', $current_date)]; // 周几显示
            }

            // 生成每天的可预约时间
            $timeList = [];
            $last_time = $closing_time - ($interval * 60); // 最后一个可预约时间

            for ($time = $opening_time; $time < $closing_time; $time += $interval * 60) {
                // 如果当前时间已经过了这个预约时间，则跳过
                if ($current_date == strtotime('today') && $time <= time()) {
                    continue; // 跳过已过时间
                }

                // 如果当前时间超过最后一个可预约时间，则只能显示到关门时间为止
                if ($time > $last_time) {
                    $timeList[] = ['num' => count($timeList) + 1, 'time' => date('H:i', $closing_time)]; // 加入关门时间
                    break; // 结束循环
                }
                $timeList[] = ['num' => count($timeList) + 1, 'time' => date('H:i', $time)]; // 将时间和自增的 num 放入数组
            }

            // 如果最后一个时间不是关门时间，且之前还有时间，添加关门时间
            if (!empty($timeList) && end($timeList)['time'] !== date('H:i', $closing_time)) {
                $timeList[] = ['num' => count($timeList) + 1, 'time' => date('H:i', $closing_time)]; // 加入关门时间
            }

            // 将日期、星期几和可预约时间组合成一个对象，并添加到结果数组中
            $dateList[] = [
                'date' => $date_label,          // 显示“月-日”
                'weekday' => $weekday_label,    // 显示“今天”、“明天”、“后天”或“周几”
                'available_times' => $timeList   // 可预约时间列表
            ];
        }
        // 输出结果
        $this->success('请求成功', $dateList);
    }


    //查询预约
    public function find_reser(){

        if (!$lights_id = input('lights_id')) {
            $this->error(__('请先扫灯码'));
        }
        $lights = Lights::where('id', $lights_id)->find();
        if(!$lights){
            $this->error(__('灯码不存在'));
        }
        $shop_id = $lights['shop_id'];

        if (!$phone = input('phone')) {
            $this->error(__('请输入手机号后四位'));
        }
       $info= \app\common\model\Reservations::where('shop_id',$shop_id)->field('id,shop_id,room_id,start_time,end_time')
           ->where('deposit_status','=',1)
           ->where('reservation_status','<>',2)
           ->where('phone', 'LIKE', '%' . input('phone'))
           ->find();
        if($info){
            $info['shop_name'] = ManystoreShop::where('id', $info['shop_id'])->value('name');
            $room = Rooms::where('id', $info['room_id'])->find();
            $info['room_name'] = $room['title'];
            $info['theme'] = $room['theme'];
            $info['code']=$lights['code'];
            $info['date']=timesf($info['start_time'],$info['end_time']);

            //查询正在玩的列表

            $occupants = Occupants::field('id')->with(['user'])->where('occupants.status', '=', 0)
                ->where('shop_id', '=', $shop_id)
                ->where('room_id',$info['room_id'])
                ->select(); // 获取所有正在玩的用户

            // 查找已预约的人
            $reservations = Db::table('fa_reservations')
                ->where('start_time', '<=', $info['start_time'])
                ->where('end_time', '>=', $info['end_time'])
                ->where('room_id', '=', $info['room_id'])
                ->value('(number_of_people-number_used)')?? 0; // 获取正在进行的预约

            // 获取正在玩的用户人数
            $occupied_count = count($occupants);
            $reserved_count = $reservations; // 预约人数

            // 获取空闲位置数量
            $total_positions = $room['capacity']; // 包间总位置
            $free_count = $total_positions - ($occupied_count + $reserved_count); // 计算空闲位置数

            // 构建返回的 occupants 信息
            $occupant_info = [];

            // 添加正在使用的用户
            foreach ($occupants as $occupant) {
                $occupant->getRelation('user')->visible(['username', 'avatar','id','link_img','gender']);
                $occupant_info[] = [
                    'user_info' => $occupant, // 用户信息
                    'status' => '正在使用' // 状态
                ];
            }
            // 添加已预约的用户
            for ($i = 0; $i<$reserved_count; $i++) {
                $occupant_info[] = [
                    'status' => '已预约' // 状态
                ];
            }
            // 添加空闲位置信息
            for ($i = 0; $i < $free_count; $i++) {
                $occupant_info[] = [
                    'status' => '空闲' // 状态
                ];
            }
            $info['occupants_info'] = $occupant_info; // 添加占用和空闲信息
            $this->success('请求成功', $info);
        }else{
            $this->error(__('未找到预约记录'));
        }
    }


    //预约选人数
    public function num_list(){
        $data=[];
        $num=(12-input('num'));
        for ($i=1;$i<=$num;$i++){
            $data[]=$i;
        }
        $this->success('请求成功', $data);
    }

    //预约取消
    public function reservation_cancel(){
        db::startTrans();
        if (!$id= input('id')) {
            $this->error(__('请选择预约记录'));
        }
       $Reservations= \app\common\model\Reservations::where('id',$id)->find();

        if($Reservations['deposit_status']==0){
           \app\common\model\Reservations::where('id',$id)->where('deposit_status','=',0)->update(['deposit_status'=>2,'cancel_time'=>time()]);
            db::commit();
            $this->success('请求成功', []);
        }

        if($Reservations['deposit_status']!=1&&$Reservations['reservation_status']!=0){
            $this->error(__('当前记录无法退款'));
        }

        $longtime=time()-strtotime($Reservations['start_time']);
        // 判断是否小于6个小时
        if ($longtime < 21600) {
          $penalty_fee=round($Reservations['deposit']*0.3,2);
        }else{
          $penalty_fee=0;
        }
        $balance_deduction=$Reservations['balance_deduction'];//余额付了多少钱
        $final_amount=$Reservations['final_amount'];//微信支付了多少钱
        if ($penalty_fee == 0) {
            // 没有违约金，全部退款
            $balance_refund = $balance_deduction; // 全部余额退款
            $wechat_refund = $final_amount; // 全部微信退款
        } else {
            // 有违约金
            if ($balance_deduction >= $penalty_fee) {
                // 如果余额足够支付违约金
                $balance_refund = $penalty_fee; // 用余额支付违约金，余额会退还
                $wechat_refund = $final_amount; // 微信退款为全额
            } else {
                // 如果余额不足以支付全部违约金
                $balance_refund = 0; // 余额不退
                $wechat_refund = $final_amount - ($penalty_fee - $balance_deduction); // 微信退款为微信支付金额减去未支付的违约金
            }
        }
        // 调用退款方法
        if ($balance_refund > 0) {
            \app\common\model\User::money($balance_refund,$this->auth->id,'取消预约');
        }
        if ($wechat_refund > 0) {
            $order=new Service();
            $result= $order->refund(order_no(), $Reservations['order_no'], $Reservations['final_amount']*100,$wechat_refund*100);
            if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
                $this->error( $result['err_code_des']);
            }
        }
        \app\common\model\Reservations::where('id','=',$Reservations['id'])->update(['deposit_status'=>2,'penalty_fee'=>$penalty_fee,'cancel_time'=>time()]);
        db::commit();
        $this->success('请求成功', []);

    }




    public function reservations_info()
    {
        $info = Article::where('type', '=', 'reservations')->field('content')->find();
        $this->success('请求成功', $info);
    }

    public function reservations_notice(){
        $info = SystemConfig::field('reservations')->find();
        $this->success('请求成功', $info);
    }




}
